document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const loginForm = document.getElementById('loginForm');
    const userInfoDisplay = document.getElementById('userInfoDisplay');

    registerForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        registerUser(username, password);
    });

    loginForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;
        loginUser(username, password);
    });

    function registerUser(username, password) {
        fetch('/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username: username, password: password })
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
        })
        .catch(error => {
            console.error('注册失败:', error);
        });
    }

    function loginUser(username, password) {
        fetch('/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username: username, password: password })
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
            if (data.success) {
                document.cookie = `session_token=${data.session_token}`;
                getUserInfo();
            }
        })
        .catch(error => {
            console.error('登录失败:', error);
        });
    }

    function getUserInfo() {
        const cookies = document.cookie.split(';');
        let sessionToken = '';
        cookies.forEach(cookie => {
            const [key, value] = cookie.split('=');
            if (key.trim() === 'session_token') {
                sessionToken = value;
            }
        });

        fetch('/user', {
            headers: {
                'Authorization': `Bearer ${sessionToken}`
            }
        })
        .then(response => response.json())
        .then(data => {
            userInfoDisplay.textContent = `用户名: ${data.username}`;
        })
        .catch(error => {
            console.error('获取用户信息失败:', error);
        });
    }
});
